-- Hook with ItemLinksDB3 to allow searching for item links based on names.

local GenieList = GenieList

function GenieList:LookupItemsInItemLinksDB3(items)
  local updated = false
  local item_id, item_name, item_link
  DEFAULT_CHAT_FRAME:AddMessage('Looking up items in ItemLinksDB3...')
  local iterator, state, start
  iterator, state, start = ItemLinksDB3.IterateDB()
  for item_id, item_data in iterator, state, start do
    item_name = ItemLinksDB3.SplitData(item_data)
    if (items[item_name] and items[item_name].id < 0) then
      -- Just to be careful, in case the database is flaw.
      _, item_link = GetItemInfo(item_id)
      if (item_link) then
        items[item_name].id = item_id
        updated = true
        DEFAULT_CHAT_FRAME:AddMessage(format('Found item: %s', item_link))
      end
    end
  end
  DEFAULT_CHAT_FRAME:AddMessage('Lookup done!')
  return updated
end

function GenieList:HookItemLinksDB3()
  -- Check for existence of ItemLinksDB3
  if (not ItemLinksDB3) then
    -- Try to load it.
    LoadAddon('Lib-ItemLinksDB3')
    -- If we still fail, bail.
    if (not ItemLinksDB) then
      DEFAULT_CHAT_FRAME:AddMessage('Missing ItemLinksDB')
      return
    end
  end
  -- Creates an extra item on the global menu.
  self.options.args.itemlinksdb3 = {
    type = 'execute',
    name = 'Lookup items in ItemLinksDB3',
    desc = 'Use ItemLinksDB3 to resolve item links for unknown items.',
    usage = '',
    order = 5,
    func = function()
      if (self:LookupItemsInItemLinksDB3(self.db.char.items)) then
        self:Refresh()
      end
    end
  }
end
